<template>
  <el-card>
    <div slot="header">
      <el-row type="flex" justify="space-between" align="middle">
        <h3>维护架构信息</h3>
        <el-row type="flex">
          <el-button
            type="text"
            size="large"
            :loading="btnLoading.submit"
            @click="handleSave"
          >保存</el-button
          >
          <el-button
            v-show="isEnterFromAuditNotPassedPage()"
            type="text"
            size="large"
            :loading="btnLoading.submit"
            @click="returnPrevPage"
          >返回</el-button
          >
        </el-row>
      </el-row>
    </div>
    <el-backtop target="#app .i-layout-content-main">
      <i class="el-icon-top"></i>
    </el-backtop>
    <div class="schema-info-body">
      <el-form
        :model="formData"
        :rules="formRules"
        ref="formData"
        label-width="150px"
      >
        <!-- 商品类型 -->
        <el-row type="flex">
          <el-form-item label="商品类型：" prop="productType">
            <el-select
              class="product_type_select"
              v-model="formData.productType"
              placeholder="请选择"
              @change="handleSelectProductType"
            >
              <el-option
                v-for="item in productTypeOptions"
                :key="item.optionValue"
                :label="item.optionHtml"
                :value="item.optionValue"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-row>
        <!-- 集散地 是否采集 -->
        <el-row type="flex">
          <el-form-item label="集散地：" prop="disCentre">
            <el-input
              v-model.trim="formData.disCentre"
              placeholder="请输入集散地"
            ></el-input>
          </el-form-item>
          <el-form-item label="是否采集：" prop="centralBuyState">
            <el-radio-group v-model="formData.centralBuyState">
              <el-radio label="1">是</el-radio>
              <el-radio label="2">否</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-row>
        <!-- 品牌 系列 -->
        <el-row type="flex">
          <el-form-item label="品牌：" prop="brandName">
            <RemoteSelect
              ref="brandRemoteRef"
              placeholder="请选择品牌"
              :optionKeys="['brandName', 'uuid']"
              :echoValue="formData.brandUuid"
              :echoOptions="[formData.brandName, formData.brandUuid]"
              :remoteSelectOptions="remoteOptionsByBrand"
              :handleClickButton="handleChooseBrand"
              @getSelect="getBrandInfoByRemote"
            />
          </el-form-item>
          <el-form-item label="系列：" prop="brandseries" v-loading=seriesLoading>
            <el-select
              v-model="formData.brandseriesUuid"
              placeholder="请选择"
              @change="handleChooseBrandseries"
            >
              <el-option
                v-for="item in brandseriesOptions"
                :key="item.seriesUuid"
                :label="item.series"
                :value="item.seriesUuid"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-row>
        <!-- 商品名称 -->
        <el-row>
          <el-form-item label="商品名称：" prop="productName">
            <el-input
              class="self_lang_input"
              placeholder="请输入商品名称"
              v-model.trim="formData.productName"
              @blur="handleInputProductName"
            >
              <template slot="prepend">{{
                formData.joinBrandName || "暂无品牌"
              }}</template>
            </el-input>
          </el-form-item>
        </el-row>
        <!-- 是否包含品牌 -->
        <el-row>
          <el-form-item label="是否包含品牌：" prop="productNameType">
            <el-radio-group
              v-model="formData.productNameType"
              @change="handleSwitchIsIncludesBrand"
            >
              <el-radio disabled label="1">包含</el-radio>
              <el-radio disabled label="2">不包含</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-row>
        <!-- 商品关键词-别名 -->
        <el-row style="padding-left: 30px;">
          <KeywordsAdd
            ref="keywordRef"
            :dataSource="formData.keywordInfoDTO"
            :productName="getFullProductName()"
          />
        </el-row>
        <!-- 助记码 -->
        <el-row>
          <el-form-item label="助记码：" prop="helpCode">
            <el-input
              disabled
              class="self_lang_input"
              v-model.trim="formData.helpCode"
              placeholder="请输入助记码"
              @input="handleVerificationReplaceCn"
            ></el-input>
            <span id="help-code-loading"></span>
          </el-form-item>
        </el-row>
        <!-- 副标题 -->
        <el-row>
          <el-form-item label="副标题：" prop="subtitle">
            <el-input
              class="self_lang_input"
              v-model.trim="formData.subtitle"
              placeholder="请输入副标题"
            ></el-input>
          </el-form-item>
        </el-row>
        <!-- 加价类型 -->
        <el-row>
          <el-form-item label="加价类型：">
            <span>{{ plainText.addPriceTypeStr }}</span>
          </el-form-item>
        </el-row>
        <!-- 是否采购多计量 -->
        <el-row>
          <el-form-item label="是否采购多计量：">
            <span>{{ plainText.isPurchaseMultiUnitStr }}</span>
          </el-form-item>
        </el-row>
        <!-- 主计量单位 -->
        <el-row type="flex">
          <el-form-item label="主计量单位：">
            <div class="div-min-width">{{ plainText.mainUnit }}</div>
          </el-form-item>
          <el-form-item label="主单位小数位：">
            <div>{{ plainText.mainUnitDecimalsStr }}</div>
          </el-form-item>
        </el-row>
        <!-- 辅计量单位 -->
        <el-row v-show="isShowSideUnit()" type="flex">
          <el-form-item label="辅计量单位：">
            <div class="div-min-width">{{ plainText.sideUnit }}</div>
          </el-form-item>
          <el-form-item label="辅计量单位小数位：">
            <div>{{ plainText.sideUnitDecimalsStr }}</div>
          </el-form-item>
        </el-row>
        <!-- 标签 -->
        <!-- <el-row>
          <el-form-item label="标签：">
            <span>{{ plainText.labelListStr }}</span>
          </el-form-item>
        </el-row> -->
      </el-form>
      <!-- <el-card shadow="never" v-show="skuSpecInfo.list.length !== 0"> -->
        <!-- <div slot="header"> -->
          <!-- <span>SPU下已有SKU展示</span> -->
        <!-- </div> -->
        <!-- <SkuTable
          :tableHeight="395"
          :columns="skuSpecInfo.columns"
          :dataSource="skuSpecInfo.list"
        /> -->
        <MaintainSpecTable
          ref="specTableRef"
          :header-list="skuSpecInfo.headerList"
          :sku-list="skuSpecInfo.skuList"
        />
      <!-- </el-card> -->
    </div>
    <!-- 选择品牌弹框 -->
    <SelectBrandDialog
      :visible.sync="brandVisible"
      :categoryUuid="plainText.categoryUuid"
      :canSearchAll="canSearchAllByProductType"
      @getBrandInfo="getBrandInfoByBrandDialog"
    />
  </el-card>
</template>
<script>
import SkuTable from '@/components/skusTable';
import KeywordsAdd from '@/components/KeywordsAdd';
import RemoteSelect from '@/pages/commodity/components/RemoteSelect';
import SelectBrandDialog from '@/pages/commodity/components/SelectBrandDialog';
import MaintainSpecTable from '@/pages/commodity/components/MaintainSpecTable';
import {
  getBrandInfoListService,
  getHelpCodeInfoService,
  getSpuRelSeriesInfoService
} from '@/api/commodity/common';
import {
  getSchemaInfoService,
  submitSchemaInfoService
} from '@/api/commodity/commodityAccessManage/commodityToPerfect';
export default {
  components: {
    SelectBrandDialog,
    SkuTable,
    KeywordsAdd,
    RemoteSelect,
    MaintainSpecTable
  },
  data () {
    return {
      formData: { // 表单数据
        productType: '', // 商品类型
        disCentre: '', // 集散地
        centralBuyState: '', // 是否采集
        brandName: '', // 品牌名称
        brandUuid: '', // 品牌编码
        joinBrandName: '', // 商品名称包含品牌时，所取用的品牌名称
        brandseries: '', // 系列名称
        brandseriesUuid: '', // 系列编码
        productName: '', // 商品名称
        productNameType: '', // 是否包含品牌
        helpCode: '', // 助记码
        subtitle: '', // 副标题
      },
      plainText: { // 纯文本
        productUuid: '', // uuid
        categoryUuid: '', // 品类路径
        spuNo: '', // spu编码
        addPriceType: '', // 加价类型
        addPriceTypeStr: '', // 加价类型文本
        isPurchaseMultiUnit: '', // 是否采购多计量， 1-是；2-否
        isPurchaseMultiUnitStr: '', // 是否采购多计量文本
        isSaleMultiUnit: '', // 是否采销多计量， 1-是；2-否
        mainUnit: '', // 主计量名称
        mainUnitDecimalsStr: null, // 主计量小数位
        sideUnit: '', // 辅计量名称
        sideUnitDecimalsStr: null, // 辅计量小数位
        labelListStr: '', // 标签集合文本
      },
      productTypeOptions: [], // 商品类型下拉options
      brandseriesOptions: [], // 系列下拉options
      brandVisible: false, // 品牌弹框开关
      canSearchAllByProductType: false, // 根据商品类型决定是否可全查品牌，默认不可全查
      formRules: {
        productType: [{ required: true, message: '商品类型不能为空' }],
        brandName: [{ required: true, message: '品牌不能为空' }],
        productName: [{ required: true, message: '商品名称不能为空' }],
        subtitle: [{ required: true, message: '副标题不能为空' }]
      },
      btnLoading: { // 按钮loading
        submit: false // 提交
      },
      skuSpecInfo: { // SKU规格信息
        columns: [
          { title: 'SKU编码', key: 'skuNo' },
          { title: '规格', key: 'specDetailStr' }
        ],
        list: []
      },
      seriesLoading: false, // 系列下拉加载loading
    }
  },
  mounted () {
    this.loadInitDataInMounted();
  },
  methods: {
    // 是从审核驳回页面进入
    isEnterFromAuditNotPassedPage () {
      return this.$route.query.type === 'auditNotPassed';
    },
    // 展示辅计量单位
    isShowSideUnit () {
      const { isPurchaseMultiUnit, isSaleMultiUnit } = this.plainText;
      if (isPurchaseMultiUnit === '1' || isSaleMultiUnit === '1') {
        return true;
      }
      return false;
    },
    // 内容为空 by 是否包含品牌
    isEmptyByIncludeBrandState () {
      const { joinBrandName, productName, productNameType } = this.formData;
      const boolByProductNameType = {
        '1': joinBrandName && productName,
        '2': productName
      }
      return !boolByProductNameType[productNameType];
    },
    // 选择商品类型
    handleSelectProductType () {
      // 切换商品类型清空所选品牌
      this.formData.brandName = '';
      this.formData.brandUuid = '';
      this.formData.joinBrandName = '';
      this.$refs?.brandRemoteRef?.clearOptions && this.$refs.brandRemoteRef.clearOptions()
      this.formData.brandseriesUuid = ''
      this.brandseriesOptions = []
    },
    // 选择品牌
    handleChooseBrand () {
      if (this.formData.productType === '10') { // 如果商品类型是项目商品（10）的时候，品牌可查全部
        this.canSearchAllByProductType = true;
      } else {
        this.canSearchAllByProductType = false;
      }
      this.brandVisible = true;
    },
    // 选择系列
    handleChooseBrandseries () {
      const brandseriesInfo = this.brandseriesOptions.find(item => item.seriesUuid === this.formData.brandseriesUuid)
      this.formData.brandseries = brandseriesInfo?.series ?? ''
    },
    // 输入商品名称
    handleInputProductName () {
      if (!this.formData.joinBrandName || !this.formData.productName) {
        this.$set(this.formData, 'helpCode', '');
        return false;
      }
      this.getFormHelpCode();
    },
    // 切换是否包含品牌
    handleSwitchIsIncludesBrand () {
      if (this.isEmptyByIncludeBrandState()) { // 根据是否包含品牌判断对应内容是否为空
        this.$set(this.formData, 'helpCode', '');
        return false;
      }
      this.getFormHelpCode();
    },
    // 检测助记码是否有输入中文事件，输入中文就替换为空
    handleVerificationReplaceCn () {
      this.$set(this.formData, 'helpCode', _.replace(
        this.formData.helpCode,
        /[\u4E00-\u9FA5]/g,
        ''
      ));
    },
    // 保存
    handleSave () {
      this.$refs.formData.validate((valid) => {
        this.warnMessageByEmptyItem();
        if (valid) {
          this.saveStructureInfo();
        }
      })
    },
    // 返回上一页
    returnPrevPage () {
      const { type } = this.$route.query;
      if (!type) { return false; }
      const routerNameMappings = {
        'toWait': 'commodityNotPerfection',
        'auditNotPassed': 'commodityRejected'
      }
      this.$router.push({ name: routerNameMappings[type] });
    },
    // 警告提示表单为空的必填项
    warnMessageByEmptyItem () {
      const requiredKeys = Object.keys(this.formRules);
      for (let i = 0; i < requiredKeys.length; i++) {
        if (!this.formData[requiredKeys[i]]) {
          this.$message.warning(this.formRules[requiredKeys[i]][0].message);
          break;
        }
      }
    },
    // 保存架构信息
    async saveStructureInfo () {
      const { productUuid, spuNo } = this.plainText;
      const keywordInfoDTO = await this.$refs.keywordRef.getResultBySubmit() || {};
      const skuInputList = this.$refs?.specTableRef?.getSkuInputList() ?? []
      const data = {
        productUuid,
        spuNo,
        ...this.formData,
        keywordInfoDTO,
        skuInputList,
      }
      const retStatus = await submitSchemaInfoService(
        data,
        state => { this.btnLoading.submit = state; }
      );
      if (retStatus) {
        this.$message.success('保存成功');
        this.returnPrevPage();
      }
    },
    // 选择品牌后清空已选择的系列值
    clearBrandseriesByBrandSelected () {
      this.formData.brandseries = '';
      this.formData.brandseriesUuid = '';
    },
    // 加载数据在mounted时期
    loadInitDataInMounted () {
      this.getAllPageInfo(this.$route.query.productUuid);
    },
    // 设置表单数据（formData）
    setFormData (data) {
      const {
        productType, // 商品类型
        disCentre, // 集散地
        centralBuyState, // 是否采集
        brandName, // 品牌名称
        brandUuid, // 品牌编码
        joinBrandName,
        brandseries, // 系列名称
        brandseriesUuid, // 系列编码
        productName, // 商品名称
        productNameType, // 是否包含品牌
        helpCode, // 助记码
        subtitle, // 副标题
        keywordInfoDTO, // 商品关键词相关信息
      } = data;
      this.formData = {
        productType, // 商品类型
        disCentre, // 集散地
        centralBuyState, // 是否采集
        brandName, // 品牌名称
        brandUuid, // 品牌编码
        joinBrandName,
        brandseries, // 系列名称
        brandseriesUuid, // 系列编码
        productName, // 商品名称
        productNameType, // 是否包含品牌
        helpCode, // 助记码
        subtitle, // 副标题
        keywordInfoDTO, // 商品关键词相关信息
      }
    },
    // 设置纯文本（plainText）
    setPlainText (data) {
      const {
        productUuid,
        categoryUuid,
        spuNo,
        addPriceType, // 加价类型
        isPurchaseMultiUnit, // 是否采购多计量， 1-是；2-否
        isSaleMultiUnit, // 是否采销多计量， 1-是；2-否
        mainUnit: { mainUnit, mainUnitDecimalsStr }, // 主计量单位
        sideUnit: { sideUnit, sideUnitDecimalsStr }, // 辅计量单位
        labelList, // 标签集合
      } = data;
      this.plainText = {
        productUuid,
        categoryUuid,
        spuNo,
        addPriceType, // 加价类型
        isPurchaseMultiUnit, // 是否采购多计量， 1-是；2-否
        isSaleMultiUnit, // 是否采销多计量， 1-是；2-否
        mainUnit, // 主计量单位名称
        mainUnitDecimalsStr, // 主计量小数位
        sideUnit, // 辅计量单位名称
        sideUnitDecimalsStr, // 辅计量小数位
        labelListStr: this.getLabelListStr(labelList), // 标签集合
      }
    },
    // 设置商品类型options
    setProductTypeOptions (productTypeOptions) {
      this.productTypeOptions = productTypeOptions || [];
    },
    // 设置系列下拉options
    setBrandseriesOptions (brandseriesOptions) {
      this.brandseriesOptions = brandseriesOptions || [];
    },
    // 设置SKU规格列表信息
    setInfoBySkuSpec (retData) {
      this.skuSpecInfo.skuList = retData?.skuList ?? []
      this.skuSpecInfo.headerList = retData?.specAttrHeaderList ?? []
    },
    // 获取完整商品名称
    getFullProductName () {
      if (this.formData.productNameType === '1') { // 包含品牌名称
        return this.formData.joinBrandName + this.formData.productName;
      }
      if (this.formData.productNameType === '2') { // 不包含品牌名称
        return this.formData.productName;
      }
    },
    // 获取系列下拉options
    async getBrandseriesOptions (brandUuid) {
      const data = {
        categoryUuid: this.plainText.categoryUuid,
        brandUuid,
        productType: this.formData.productType
      }
      const loadingFn = state => { this.seriesLoading = state }
      const res = await getSpuRelSeriesInfoService(data, loadingFn)
      if (res?.retData) {
        this.setBrandseriesOptions(res.retData);
        this.brandseriesOptions.length == 1 && this.$set(this.formData, 'brandseriesUuid', this.brandseriesOptions[0].seriesUuid) // 品牌下只有一个系列，自动代入该系列
      }
    },
    // 获取标签集合名称
    getLabelListStr (list) {
      if (!list) { return false; }
      return list.map(item => item.labelName).filter(item => item).join(',');
    },
    // 获取所有回显文本列
    getAllEchoOfFormItem () {
      let getAddPriceTypeStr = this.getEchoText();
      let getPurchaseMultiUnitStr = this.getEchoText();
      const { addPriceType, isPurchaseMultiUnit } = this.plainText;
      this.plainText.addPriceTypeStr = getAddPriceTypeStr(
        addPriceType, { oneText: '固定金额', twoText: '比例' }
      );
      this.plainText.isPurchaseMultiUnitStr = getPurchaseMultiUnitStr(isPurchaseMultiUnit);
      // 消除闭包
      getAddPriceTypeStr = null;
      getPurchaseMultiUnitStr = null;
    },
    // 获取回显文本
    getEchoText (oneValue = '1', twoValue = '2') {
      return function (val, label = { oneText: '是', twoText: '否' }) {
        if (!val) { return ''; }
        const textMappings = {
          [oneValue]: label.oneText,
          [twoValue]: label.twoText
        }
        return textMappings[val] || '';
      }
    },
    // 模糊搜索品牌下拉
    async remoteOptionsByBrand (queryString, loadingFn) {
      const data = {
        nowPage: 1,
        pageShow: 20,
        brandName: queryString,
        categoryUuid: this.formData.productType === '10' ? '' : this.plainText.categoryUuid,
        notInUuids: ''
      }
      const res = await getBrandInfoListService(data, loadingFn);
      return res?.retData?.results ?? []
    },
    // 获取品牌 by 远程模糊搜索
    getBrandInfoByRemote (data) {
      this.setBrandInfo({
        name: data.brandName,
        uuid: data.uuid,
        joinBrandName: data.factoryInfluenceMore === '1' ? data.factoryBrandName : data.brandName,
        productNameType: data.productNameType,
        factoryInfluenceMore: data?.factoryInfluenceMore
      });
    },
    // 获取品牌 by 品牌弹框
    getBrandInfoByBrandDialog (brandInfo) {
      this.setBrandInfo(brandInfo);
    },
    // 设置品牌信息
    setBrandInfo (brandInfo) {
      const { name, uuid, joinBrandName, productNameType, factoryInfluenceMore, factoryBrandName } = brandInfo ?? {}
      if (!factoryInfluenceMore) return this.$message.warning('厂家品牌影响力为空，请维护厂家品牌影响力信息')
      if (factoryInfluenceMore == '1' && !factoryBrandName) return this.$message.warning('当厂家品牌影响力大于品牌时，厂家品牌名称不能为空')
      this.formData.brandName = name;
      this.formData.brandUuid = uuid;
      this.formData.joinBrandName = joinBrandName;
      this.formData.productNameType = productNameType;
      if (this.formData.productName) { // 如果有品牌名称，再获取一次助记码
        this.getFormHelpCode();
      }
      this.clearBrandseriesByBrandSelected(); // 清空已选择的系列
      this.getBrandseriesOptions(uuid); // 获取系列下拉options
    },
    // 获取助记码
    async getFormHelpCode () {
      const { joinBrandName, productName, productNameType, productType } = this.formData;
      const data = {
        brandName: joinBrandName,
        productName,
        productNameType,
        productType
      };
      const retData = await getHelpCodeInfoService(data, '.schema-info-body');
      if (retData) {
        this.$set(this.formData, 'helpCode', retData.helpCode);
      }
    },
    // 获取所有页面信息
    async getAllPageInfo (productUuid) {
      const retData = await getSchemaInfoService(productUuid, '.schema-info-body');
      if (retData) {
        this.setFormData(retData);
        this.setPlainText(retData);
        // this.setProductTypeOptions(retData.productTypeOptions);
        // 选择商品类型 不让选择 项目商品 https://www.tapd.cn/41685229/prong/stories/view/1141685229001232400
        const productTypeOptions = (retData.productTypeOptions ?? []).filter(item => item.optionValue != '10')
        this.setProductTypeOptions(productTypeOptions)
        this.setBrandseriesOptions(retData.brandSeriesSelList);
        this.setInfoBySkuSpec(retData);
        this.getAllEchoOfFormItem();
      }
    },
  }
}
</script>
<style lang="less" scoped>
.schema-info-body {
  /* 商品类型下拉框样式 */
  .product_type_select {
    /deep/ .el-input__inner {
      width: 300px;
    }
  }
  .input_button_color {
    color: #ffffff;
    background-color: #5a9cf8;
  }
  /* 商品名称输入框样式 */
  .self_lang_input {
    width: 60%;
  }
  .div-min-width {
    min-width: 300px;
  }
}
/deep/ .el-card__header {
  padding: 10px 20px;
}
</style>
